package com.vids.controller;

import cn.hutool.core.collection.CollUtil;
import com.vids.utils.StringUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.vids.alarm.MyRejected;
import com.vids.constant.Urlconstant;
import com.vids.constant.VIIDRespEnum;
import com.vids.model.entity.ImageBusiness;
import com.vids.model.entity.Person;
import com.vids.model.param.*;
import com.vids.model.response.PersonBatch;
import com.vids.model.response.ResponseStatus;
import com.vids.model.vo.SubImageInfoVo;
import com.vids.service.IImageBusinessService;
import com.vids.service.IPersonService;
import com.vids.utils.BeanUtilss;
import com.vids.utils.BussinessIDGennelUtil;
import com.vids.utils.ImageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 人像 前端控制器
 * </p>
 *
 */
@Slf4j
@RestController
@RequestMapping("/VIID")
@RequiredArgsConstructor
public class PersonController {

    public final static String fCode = "02";
    public final static String cCode = "06";

    public final static String type = "11";

    private String appId = "42010000005040000000";


    private final IPersonService iPersonService;

    private final IImageBusinessService imageBusinessService;

//    private Map<String,Long> map = AlarmUtils.newMap(); 未用到 edward 注掉
    private String endTime;

    // 线程池
    ThreadPoolExecutor pool;

    {
        try {
            pool = new ThreadPoolExecutor(
                            15,
                            20,
                            60,
                            TimeUnit.SECONDS,
                            new LinkedBlockingQueue<Runnable>()
                            , new MyRejected()
                    );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 校验参数
     *
     * @param status
     */
    private void validateParams(Person person, ResponseStatus status) {
	StringBuffer sb = new StringBuffer();
	if (StringUtils.isEmpty(person.getPersonID())) {
	    sb.append("PersonID必填；");
	}
	if (person.getInfoKind() == null) {
	    sb.append("InfoKind必填；");
	}
	if (StringUtils.isEmpty(person.getSourceID())) {
	    sb.append("SourceID必填；");
	}
	if (person.getIsSuspectedTerrorist() == null) {
	    sb.append("IsSuspectedTerrorist必填；");
	}
	if (person.getIsCriminalInvolved() == null) {
	    sb.append("IsCriminalInvolved必填；");
	}
	if (person.getIsDetainees() == null) {
	    sb.append("IsDetainees必填；");
	}
	if (person.getIsVictim() == null) {
	    sb.append("IsVictim必填；");
	}
	if (person.getIsSuspiciousPerson() == null) {
	    sb.append("IsSuspiciousPerson必填；");
	}
	if (person.getInfoKind() != null && person.getInfoKind() == 1) {
	    if (StringUtils.isEmpty(person.getDeviceID())) {
		sb.append("自动采集时，DeviceID必填；");
	    }
	    if (person.getLeftTopX() == null) {
		sb.append("自动采集时，LeftTopX必填；");
	    }
	    if (person.getLeftTopY() == null) {
		sb.append("自动采集时，LeftTopY必填；");
	    }
	    if (person.getRightBtmX() == null) {
		sb.append("自动采集时，RightBtmX必填；");
	    }
	    if (person.getRightBtmY() == null) {
		sb.append("自动采集时，RightBtmY必填；");
	    }
	}
	if (person.getLeftTopX() != null && !person.getLeftTopX().toString().matches("^[0-9]+$")) {
	    sb.append("LeftTopX字段为数字；");
	}
	if (person.getLeftTopY() != null && !person.getLeftTopY().toString().matches("^[0-9]+$")) {
	    sb.append("LeftTopY字段为数字；");
	}
	if (person.getRightBtmX() != null && !person.getRightBtmX().toString().matches("^[0-9]+$")) {
	    sb.append("RightBtmX字段为数字；");
	}
	if (person.getRightBtmY() != null && !person.getRightBtmY().toString().matches("^[0-9]+$")) {
	    sb.append("RightBtmY字段为数字；");
	}
	if (person.getInfoKind() != null && person.getInfoKind() == 2) {
	    if (person.getLocationMarkTime() == null) {
		sb.append("人工采集时，LocationMarkTime必填；");
	    }
	}
	if (!StringUtils.isEmpty(person.getPersonID())) {
	    if (person.getPersonID().length() != 48) {
		sb.append("PersonID字段长度不为48；");
	    }
	    if (!person.getPersonID().matches("^[0-9]+$")) {
		sb.append("PersonID字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(person.getSourceID())) {
	    if (person.getSourceID().length() != 41) {
		sb.append("SourceID字段长度不为41；");
	    }
	    if (!person.getSourceID().matches("^[0-9]+$")) {
		sb.append("SourceID字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(person.getDeviceID())) {
	    if (person.getDeviceID().length() != 20) {
		sb.append("DeviceID字段长度不为20；");
	    }
	    if (!person.getDeviceID().matches("^[0-9]+$")) {
		sb.append("DeviceID字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(person.getNativeCityCode())) {
	    if (person.getNativeCityCode().length() != 6) {
		sb.append("NativeCityCode字段长度不为6；");
	    }
	    if (!person.getNativeCityCode().matches("^[0-9]+$")) {
		sb.append("NativeCityCode字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(person.getResidenceAdminDivision())) {
	    if (person.getResidenceAdminDivision().length() != 6) {
		sb.append("ResidenceAdminDivision字段长度不为6；");
	    }
	    if (!person.getResidenceAdminDivision().matches("^[0-9]+$")) {
		sb.append("ResidenceAdminDivision字段为纯数字；");
	    }
	}
	if (!StringUtils.isEmpty(person.getEscapedCriminalNumber())
		&& person.getEscapedCriminalNumber().length() != 23) {
	    sb.append("EscapedCriminalNumber字段长度不为23；");
	}
	if (!StringUtils.isEmpty(person.getSuspectedTerroristNumber())
		&& person.getSuspectedTerroristNumber().length() != 19) {
	    sb.append("SuspectedTerroristNumber字段长度不为19；");
	}
//	if (!StringUtils.isEmpty(person.getIDType()) && person.getIDType().length() != 3) {
//	    sb.append("IDType字段长度不为3；");
//	}
	if (!StringUtils.isEmpty(person.getEthicCode()) && person.getEthicCode().length() != 2) {
	    sb.append("EthicCode字段长度不为2；");
	}
	if (!StringUtils.isEmpty(person.getNationalityCode())
		&& person.getNationalityCode().length() != 3) {
	    sb.append("NationalityCode字段长度不为3；");
	}
	// ChineseAccentCode 6
	if (!StringUtils.isEmpty(person.getChineseAccentCode())
		&& person.getChineseAccentCode().length() != 6) {
	    sb.append("ChineseAccentCode字段长度不为6；");
	}
	if (!StringUtils.isEmpty(person.getJobCategory()) && person.getJobCategory().length() != 3) {
	    sb.append("JobCategory字段长度不为3；");
	}
	// FaceStyle 4
	if (!StringUtils.isEmpty(person.getFaceStyle()) && person.getFaceStyle().length() != 4) {
	    sb.append("FaceStyle字段长度不为4；");
	}
	// FacialFeature <40
	if (!StringUtils.isEmpty(person.getFacialFeature()) && person.getFacialFeature().length() > 40) {
	    sb.append("FacialFeature字段长度不能大于40；");
	}
	// PhysicalFeature < 200
	if (!StringUtils.isEmpty(person.getFacialFeature()) && person.getFacialFeature().length() > 200) {
	    sb.append("FacialFeature字段长度不能大于200；");
	}
	// ImmigrantTypeCode 2
	if (!StringUtils.isEmpty(person.getImmigrantTypeCode())
		&& person.getImmigrantTypeCode().length() != 2) {
	    sb.append("ImmigrantTypeCode字段长度不为2；");
	}
	// CriminalInvolvedSpecilisationCode 2
	if (!StringUtils.isEmpty(person.getCriminalInvolvedSpecilisationCode())
		&& person.getCriminalInvolvedSpecilisationCode().length() != 2) {
	    sb.append("CriminalInvolvedSpecilisationCode字段长度不为2；");
	}
	// BodySpeciallMark 7
	if (!StringUtils.isEmpty(person.getBodySpeciallMark())
		&& person.getBodySpeciallMark().length() != 7) {
	    sb.append("BodySpeciallMark字段长度不为7；");
	}
	// CrimeMethod 4
	if (!StringUtils.isEmpty(person.getCrimeMethod()) && person.getCrimeMethod().length() != 4) {
	    sb.append("CrimeMethod字段长度不为4；");
	}
	// CrimeCharacterCode 3
	if (!StringUtils.isEmpty(person.getCrimeCharacterCode())
		&& person.getCrimeCharacterCode().length() != 3) {
	    sb.append("CrimeCharacterCode字段长度不为3；");
	}
	// DetaineesSpecialIdentity 2
	if (!StringUtils.isEmpty(person.getDetaineesSpecialIdentity())
		&& person.getDetaineesSpecialIdentity().length() != 2) {
	    sb.append("DetaineesSpecialIdentity字段长度不为2；");
	}
	// MemberTypeCode 2
	if (!StringUtils.isEmpty(person.getMemberTypeCode()) && person.getMemberTypeCode().length() != 2) {
	    sb.append("MemberTypeCode字段长度不为2；");
	}
	// VictimType 3
	if (!StringUtils.isEmpty(person.getVictimType()) && person.getVictimType().length() != 3) {
	    sb.append("VictimType字段长度不为3；");
	}
	// CorpseConditionCode 2
	if (!StringUtils.isEmpty(person.getCorpseConditionCode())
		&& person.getCorpseConditionCode().length() != 2) {
	    sb.append("CorpseConditionCode字段长度不为2；");
	}
	// Name <50
	if (!StringUtils.isEmpty(person.getName()) && person.getName().length() > 50) {
	    sb.append("Name字段长度不能大于50；");
	}
	// UsedName <50
	if (!StringUtils.isEmpty(person.getUsedName()) && person.getUsedName().length() > 50) {
	    sb.append("UsedName字段长度不能大于50；");
	}
	// Alias <50
	if (!StringUtils.isEmpty(person.getAlias()) && person.getAlias().length() > 50) {
	    sb.append("Alias字段长度不能大于50；");
	}

//	if (!StringUtils.isEmpty(person.getEyebrowStyle()) && person.getEyebrowStyle().length() > 32) {
//	    sb.append("EyebrowStyle字段长度不能大于32；");
//	}
//	if (!StringUtils.isEmpty(person.getNoseStyle()) && person.getNoseStyle().length() > 32) {
//	    sb.append("NoseStyle字段长度不能大于32；");
//	}
//	if (!StringUtils.isEmpty(person.getMustacheStyle()) && person.getMustacheStyle().length() > 32) {
//	    sb.append("MustacheStyle字段长度不能大于32；");
//	}
//	if (!StringUtils.isEmpty(person.getLipStyle()) && person.getLipStyle().length() > 32) {
//	    sb.append("LipStyle字段长度不能大于32；");
//	}
//	if (!StringUtils.isEmpty(person.getWrinklePouch()) && person.getWrinklePouch().length() > 32) {
//	    sb.append("WrinklePouch字段长度不能大于32；");
//	}
//	if (!StringUtils.isEmpty(person.getAcneStain()) && person.getAcneStain().length() > 32) {
//	    sb.append("AcneStain字段长度不能大于32；");
//	}
//	if (!StringUtils.isEmpty(person.getFreckleBirthmark())
//		&& person.getFreckleBirthmark().length() > 32) {
//	    sb.append("FreckleBirthmark字段长度不能大于32；");
//	}
//	if (!StringUtils.isEmpty(person.getScarDimple()) && person.getScarDimple().length() > 32) {
//	    sb.append("ScarDimple字段长度不能大于32；");
//	}
//	if (!StringUtils.isEmpty(person.getOtherFeature()) && person.getOtherFeature().length() > 32) {
//	    sb.append("OtherFeature字段长度不能大于32；");
//	}
	// DetentionHouseCode =9
	if (!StringUtils.isEmpty(person.getDetentionHouseCode())
		&& person.getDetentionHouseCode().length() != 9) {
	    sb.append("DetentionHouseCode字段长度不为9；");
	}
	// IDNumber 30
//	if (!StringUtils.isEmpty(person.getIDNumber()) && person.getIDNumber().length() > 30) {
//	    sb.append("IDNumber字段长度不能大于30；");
//	}
//	// Attitude 1：平视；2：微仰；3：微俯；4：左微侧脸；5：左斜侧脸；6：左全侧脸；7：右微侧脸；8：右斜侧脸；9：右全侧脸
//	if (person.getAttitude() != null
//		&& !Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9).contains(person.getAttitude())) {
//	    sb.append("Attitude的值不正确，Attitude为，1：平视；2：微仰；3：微俯；4：左微侧脸；5：左斜侧脸；6：左全侧脸；7：右微侧脸；8：右斜侧脸；9：右全侧脸；");
//	}
//	// Similaritydegree 人脸相似度，[0，1]
//	if (person.getSimilaritydegree() != null) {
//	    if (new BigDecimal(person.getSimilaritydegree()).compareTo(new BigDecimal("0")) == -1
//		    || new BigDecimal(person.getSimilaritydegree()).compareTo(new BigDecimal("1")) == 1) {
//		sb.append("Similaritydegree的值不正确，人脸相似度，[0，1]；");
//	    }
//	}
	if (person.getIsDriver() != null && !Arrays.asList(0, 1, 2).contains(person.getIsDriver())) {
	    sb.append("IsDriver的值不正确，IsDriver为，0：否；1：是；2：不确定；");
	}
	if (person.getIsForeigner() != null && !Arrays.asList(0, 1, 2).contains(person.getIsForeigner())) {
	    sb.append("IsForeigner的值不正确，IsForeigner为，0：否；1：是；2：不确定；");
	}
	if (person.getIsSuspectedTerrorist() != null
		&& !Arrays.asList(0, 1, 2).contains(person.getIsSuspectedTerrorist())) {
	    sb.append("IsSuspectedTerrorist的值不正确，IsSuspectedTerrorist为，0：否；1：是；2：不确定；");
	}
	if (person.getIsCriminalInvolved() != null
		&& !Arrays.asList(0, 1, 2).contains(person.getIsCriminalInvolved())) {
	    sb.append("IsCriminalInvolved的值不正确，IsCriminalInvolved为，0：否；1：是；2：不确定；");
	}
	if (person.getIsDetainees() != null && !Arrays.asList(0, 1, 2).contains(person.getIsDetainees())) {
	    sb.append("IsDetainees的值不正确，IsDetainees为，0：否；1：是；2：不确定；");
	}
	if (person.getIsVictim() != null && !Arrays.asList(0, 1, 2).contains(person.getIsVictim())) {
	    sb.append("IsVictim的值不正确，IsVictim为，0：否；1：是；2：不确定；");
	}
	if (person.getIsSuspiciousPerson() != null
		&& !Arrays.asList(0, 1, 2).contains(person.getIsSuspiciousPerson())) {
	    sb.append("IsSuspiciousPerson的值不正确，IsSuspiciousPerson为，0：否；1：是；2：不确定；");
	}

	if (sb != null && !StringUtils.isEmpty(sb.toString())) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, sb.toString());
	}
    }


	/**
     * 批量新增
     *
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/Persons", produces = "application/VIID+JSON")
    public Object postList(@RequestBody PersonBatchParam param) throws Exception
	{
		List<ResponseStatus> resps = new ArrayList<ResponseStatus>();
		if (param == null || param.getPersonListObject() == null || param.getPersonListObject().getPersonObject() == null
			|| param.getPersonListObject().getPersonObject().size() == 0) {
			ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
				new Date());
			setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
			resps.add(status);
			return new ResponseEntity<Map<String, Object>>(
				BeanUtilss.objectToMap(BeanUtilss.getBatchResponseModel(resps)), HttpStatus.CREATED);
		}

		List<PersonModel> list = param.getPersonListObject().getPersonObject();
        if (CollUtil.isNotEmpty(list))
		{
            log.info("人体开始");

            for (PersonModel personModel: list)
			{
				List<SubImageInfoVo> subImageInfoObject = personModel.getSubImageList().getSubImageInfoObject();
				log.info("Persons Data=======: "+subImageInfoObject.get(0).getData());

				for (SubImageInfoVo subImageInfoVo: subImageInfoObject) {
//					ImageUtil.convertBase64ToImageAndSave(subImageInfoVo.getData(),personModel.getPersonID(),subImageInfoVo.getImageID(),"person");
				}
            }
            log.info("人体结束");
        }

//		commonSavePersonBatchModel(resps, list);
		return new ResponseEntity<Map<String, Object>>(BeanUtilss.objectToMap(BeanUtilss.getBatchResponseModel(resps)),
		HttpStatus.CREATED);
    }

    public void commonSavePersonBatchModel(List<ResponseStatus> resps, List<PersonModel> list) {
	for (PersonModel model : list) {
	    ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
		    new Date());
	    if (model == null) {
		setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
		resps.add(status);
		continue;
	    }
		PersonBatch person = BeanUtilss.transferObjectCommon(model, PersonBatch.class);
	    if (model.getSubImageList() != null && model.getSubImageList().getSubImageInfoObject() != null
		    && model.getSubImageList().getSubImageInfoObject().size() > 0) {
			person.setSubImageList(model.getSubImageList().getSubImageInfoObject());
	    }
	    try {
		if (person != null && StringUtils.isEmpty(person.getPersonID()) && person.getInfoKind() != null
			&& person.getInfoKind() == 1) {
			person.setPersonID(BussinessIDGennelUtil.createViewLibraryID(appId, fCode, true, cCode));
		} else {
		    Person TBigDataPerson2 = iPersonService.findByPersonID(person.getPersonID());
		    if (TBigDataPerson2 != null) {
			setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数PersonID重复；");
			resps.add(status);
			continue;
		    }
		}
		validateParams(person, status);
		if (status.getStatusCode().equals(VIIDRespEnum.OK.getCode())) {
		    if (status.getStatusCode().equals(VIIDRespEnum.OK.getCode())) {
				Person tBigDataPerson = BeanUtilss.transferObjectIgnoreCase(person, Person.class);
			iPersonService.save(tBigDataPerson);
			// 图片和业务对于关系
			saveImageBusiness(person.getSubImageList(), type, person.getPersonID());
			status.setId(person.getPersonID());
			status.setStatusString("新增成功；");
		    }
		}
	    } catch (Exception e) {
		setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
		log.error(" PersonController  postList  Exception {} ", e);
	    }
	    resps.add(status);
	}
    }

    /**
     * 批量修改
     *
     * @param param
     * @return
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @PutMapping(value = "/Persons", produces = "application/VIID+JSON")
    public Object putList(@RequestBody PersonBatchParam param) throws IOException {
	List<ResponseStatus> resps = new ArrayList<ResponseStatus>();
	if (param == null || param.getPersonListObject() == null || param.getPersonListObject().getPersonObject() == null
		|| param.getPersonListObject().getPersonObject().size() == 0) {
	    ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
		    new Date());
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
	    resps.add(status);
	    return BeanUtilss.getBatchResponseModel(resps);
	}
	List<PersonModel> list = param.getPersonListObject().getPersonObject();
		commonPutPersonBatchModel(resps, list);
	return BeanUtilss.getBatchResponseModel(resps);
    }

    public void commonPutPersonBatchModel(List<ResponseStatus> resps, List<PersonModel> list) {
	for (PersonModel model : list) {
	    ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
		    new Date());
	    if (model == null) {
		setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
		resps.add(status);
		continue;
	    }
	    PersonBatch person = BeanUtilss.transferObjectCommon(model, PersonBatch.class);
	    if (model.getSubImageList() != null && model.getSubImageList().getSubImageInfoObject() != null
		    && model.getSubImageList().getSubImageInfoObject().size() > 0) {
			person.setSubImageList(model.getSubImageList().getSubImageInfoObject());
	    }
	    try {
		validateParams(person, status);
		if (status.getStatusCode().equals(VIIDRespEnum.OK.getCode())) {
		    updateCommon(person, status, person.getPersonID());
		}
	    } catch (Exception e) {
		setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
		log.error(" PersonController  putList  Exception {} ", e);
	    }
	    resps.add(status);
	}
    }

    /**
     * 批量删除
     *
     * @param IDList
     * @return
     */
    @DeleteMapping(value = "/Persons", produces = "application/VIID+JSON")
    public Object deleteList(@RequestParam("IDList") String IDList) {
	List<ResponseStatus> resps = new ArrayList<ResponseStatus>();
	if (StringUtils.isEmpty(IDList)) {
	    ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
		    new Date());
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数IDList为空；");
	    resps.add(status);
	    return BeanUtilss.getBatchResponseModel(resps);
	}
	String[] ids = IDList.split(",");
	for (String id : ids) {
	    ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_15, VIIDRespEnum.OK.getCode(),
		    new Date());
	    try {
		deleteCommon(status, id);
	    } catch (Exception e) {
		setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
		log.error(" PersonController  deleteList  Exception {} ", e);
	    }
	    resps.add(status);
	}
	return BeanUtilss.getBatchResponseModel(resps);
    }

    /**
     * 单个查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/Persons/{id}", produces = "application/VIID+JSON;charset=UTF-8")
    public Object get(@PathVariable("id") String id) {
        PersonBatch person = null;
	try {
		Person tBigDataPerson = iPersonService.findByPersonID(id);
	    if (tBigDataPerson != null && !StringUtils.isEmpty(tBigDataPerson.getPersonID())) {
			person = BeanUtilss.transferObjectIgnoreCase(tBigDataPerson, PersonBatch.class);
		List<SubImageInfoVo> volist = imageBusinessService
			.findSubImageInfoVo(tBigDataPerson.getPersonID(), type);
			person.setSubImageList(volist);
	    }
	} catch (Exception e) {
	    log.error("PersonController get Exception {}", e.getMessage());
	}
	if (person == null) {
	    return new ResponseEntity<Map<String, Object>>(new HashMap<String, Object>(), HttpStatus.NO_CONTENT);
	}
	PersonParam param = new PersonParam();
	PersonModel model = BeanUtilss.transferObjectCommon(person, PersonModel.class);
	if (person.getSubImageList() != null && person.getSubImageList().size() > 0) {
	    SubImageBatchParam subImageList = new SubImageBatchParam();
	    subImageList.setSubImageInfoObject(person.getSubImageList());
	    model.setSubImageList(subImageList);
	}
	param.setPersonObject(model);
	return param;
    }

    /**
     * 单个修改
     *
     * @param param
     * @param id
     * @return
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @PutMapping(value = "/Persons/{id}", produces = "application/VIID+JSON")
    public Object put(@RequestBody PersonParam param, @PathVariable("id") String id) throws IOException {
	ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_14, VIIDRespEnum.OK.getCode(), new Date());
	if (param == null || param.getPersonObject() == null) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数person无效，没有对于数据；");
	    return BeanUtilss.getResponseModel(status);
	}
	if (StringUtils.isEmpty(id)) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数PersonID为空；");
	    return BeanUtilss.getResponseModel(status);
	}
	try {
	    PersonModel model = param.getPersonObject();
		PersonBatch person = BeanUtilss.transferObjectCommon(model, PersonBatch.class);
	    if (model.getSubImageList() != null && model.getSubImageList().getSubImageInfoObject() != null
		    && model.getSubImageList().getSubImageInfoObject().size() > 0) {
			person.setSubImageList(model.getSubImageList().getSubImageInfoObject());
	    }
	    validateParams(person, status);
	    if (status.getStatusCode().equals(VIIDRespEnum.OK.getCode())) {
		updateCommon(person, status, id);
	    }
	} catch (Exception e) {
	    setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
	}
	return BeanUtilss.getResponseModel(status);
    }

    /**
     * 单个删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/Persons/{id}", produces = "application/VIID+JSON")
    public Object delete(@PathVariable("id") String id) {
	ResponseStatus status = new ResponseStatus(Urlconstant.URL_BIG_DATA_14, VIIDRespEnum.OK.getCode(), new Date());
	if (StringUtils.isEmpty(id)) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数PersonID为空；");
	    return BeanUtilss.getResponseModel(status);
	}
	try {
	    deleteCommon(status, id);
	} catch (Exception e) {
	    log.error("PersonController delete Exception {}", e);
	    setStatus(status, VIIDRespEnum.DEVICE_ERROR, "请联系管理员；");
	}
	return BeanUtilss.getResponseModel(status);
    }

    public void deleteCommon(ResponseStatus status, String id) throws Exception {
	Person TBigDataPerson2 = iPersonService.findByPersonID(id);
	if (TBigDataPerson2 == null) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数PersonID无效，没有对于数据；");
	} else {
		iPersonService.deleteByPersonID(id);

	    // 删除 图片和业务对于关系
	    deleteImageBusiness(type, id);
	    status.setId(id);
	    status.setStatusString("删除成功；");
	}
    }

    public void updateCommon(PersonBatch person, ResponseStatus status, String id) throws Exception {
	Person TBigDataPerson2 = iPersonService.findByPersonID(id);
	if (TBigDataPerson2 == null) {
	    setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数PersonID无效，没有对于数据");
	} else {
		person.setId(TBigDataPerson2.getId());
		Person tBigDataPerson = BeanUtilss.transferObjectIgnoreCase(person, Person.class);
		iPersonService.updateById(tBigDataPerson);
	    // 图片和业务对于关系
	    saveImageBusiness(person.getSubImageList(), type, person.getPersonID());
	    status.setId(id);
	    status.setStatusString("修改成功");
	}
    }

    /**
     * 条件查询
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/Persons", produces = "application/VIID+JSON;charset=UTF-8")
    public Object getList(HttpServletRequest request) {
	Object attribute = request.getAttribute("map");
	PersonBatchParam param = null;
	if (attribute instanceof Map) {
	    Map<String, Object> map = (Map<String, Object>) attribute;
	    param = iPersonService.getPersonList(map);
	}
	if (param == null) {
	    return new ResponseEntity<Map<String, Object>>(new HashMap<String, Object>(), HttpStatus.NO_CONTENT);
	}
	return param;
    }


    /**
     * 设置返回值代码和消息 VIID 标准
     *
     * @param res
     * @param e
     * @param field
     */
    protected void setStatus(ResponseStatus res, VIIDRespEnum e, String field) {
        StringBuffer sb = new StringBuffer();
        sb.append(e.getMsg() + "[" + field + "]");
        res.setStatusCode(e.getCode());
        res.setStatusString(sb.toString());
    }

    public void saveImageBusiness(List<SubImageInfoVo> subImageList, String type, String ywId) {
        if (subImageList != null && !subImageList.isEmpty()) {
            for (SubImageInfoVo vo : subImageList) {
                if (vo == null || StringUtils.isEmpty(vo.getImageID())) {
                    continue;
                }
                ImageBusiness tBigDataImageBusiness = new ImageBusiness();
                tBigDataImageBusiness.setImageId(vo.getImageID());
                tBigDataImageBusiness.setYwId(ywId);
                tBigDataImageBusiness.setBigType(type);
                tBigDataImageBusiness.setImageType(type);
                if ("01".equals(type)) {
                    if (!StringUtils.isEmpty(vo.getType()) && Arrays
                            .asList("01", "02", "03", "04", "05", "06", "07", "08", "09").contains(vo.getType())) {
                        tBigDataImageBusiness.setImageType(vo.getType());
                    }
                }
                // 先删除
                deleteImageBusiness(type, ywId);
                // 新增
                imageBusinessService.save(tBigDataImageBusiness);
            }
        }
    }

    public void deleteImageBusiness(String type, String ywId) {
        ImageBusiness tBigDataImageBusiness = new ImageBusiness();
        tBigDataImageBusiness.setYwId(ywId);
        tBigDataImageBusiness.setBigType(type);
        imageBusinessService.deleteImageBusiness(tBigDataImageBusiness);
    }

}
